"use client";

import { useState, useRef, useMemo, useEffect } from "react";
import { Calendar } from "@/components/ui/calendar";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Textarea } from "@/components/ui/textarea";
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from "@/components/ui/context-menu";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Checkbox } from "@/components/ui/checkbox";
import { User, MessageCircle, Star, BookOpen, Plus, Diamond, ChevronDown } from "lucide-react";
import ReactMarkdown from 'react-markdown';

interface Task {
  id: string;
  text: string;
  completed: boolean;
  date: string;
}

interface UserInfo {
  name: string;
  gender: string;
  avatar: string;
}

interface UserAccount {
  id: string;
  username: string;
  password: string;
  profile: UserInfo;
}

export default function Home() {
  const [selectedDate, setSelectedDate] = useState<Date>(new Date());
  const [activeSection, setActiveSection] = useState<string>("");

  // 生成这一周的任务数据
  const generateWeeklyTasks = () => {
    const today = new Date();
    const monday = new Date(today);
    monday.setDate(today.getDate() - (today.getDay() === 0 ? 6 : today.getDay() - 1));

    const weeklyTasks: Task[] = [];
    const taskTemplates = [
      ["学数学", "复习英语单词", "阅读文章"],
      ["练习编程", "学英语语法", "完成作业"],
      ["学数学定理", "英语听力练习", "写日记", "复习笔记"],
      ["数学习题", "英语口语练习"],
      ["学数学应用题", "英语阅读理解", "整理笔记", "复习本周内容"],
      ["数学总结", "英语写作练习"],
      ["休息放松", "复习这周学习内容"]
    ];

    // 预设的完成情况（0表示未完成，1表示已完成）
    const completionStatus = [
      [1, 1, 0], // 周一：3个任务，完成2个 = 0.67
      [1, 0], // 周二：2个任务，完成1个 = 0.50
      [1, 1, 1, 0], // 周三：4个任务，完成3个 = 0.75
      [1, 1], // 周四：2个任务，完成2个 = 1.00
      [0, 1, 0, 0], // 周五：4个任务，完成1个 = 0.25
      [1, 0], // 周六：2个任务，完成1个 = 0.50
      [0, 0] // 周日：2个任务，完成0个 = 0.00
    ];

    for (let dayOffset = 0; dayOffset < 7; dayOffset++) {
      const currentDate = new Date(monday);
      currentDate.setDate(monday.getDate() + dayOffset);
      const dateString = currentDate.toDateString();

      const dayTasks = taskTemplates[dayOffset];
      const dayCompletions = completionStatus[dayOffset];

      dayTasks.forEach((taskText, taskIndex) => {
        weeklyTasks.push({
          id: `${dayOffset}-${taskIndex}`,
          text: taskText,
          completed: dayCompletions[taskIndex] === 1,
          date: dateString
        });
      });
    }

    return weeklyTasks;
  };

  const [tasks, setTasks] = useState<Task[]>(generateWeeklyTasks());
  const [newTaskText, setNewTaskText] = useState("");
  const [userInfo, setUserInfo] = useState<UserInfo>({
    name: "张三",
    gender: "男",
    avatar: ""
  });
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [currentView, setCurrentView] = useState<'login' | 'register'>('login');
  const [loginUsername, setLoginUsername] = useState("");
  const [loginPassword, setLoginPassword] = useState("");
  const [registerName, setRegisterName] = useState("");
  const [registerUsername, setRegisterUsername] = useState("");
  const [registerPassword, setRegisterPassword] = useState("");
  const [currentUser, setCurrentUser] = useState<UserAccount | null>(null);
  const [questionInput, setQuestionInput] = useState("");
  const [chatHistory, setChatHistory] = useState<Array<{id: string, type: 'user' | 'ai', message: string}>>([]);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 个性推荐搜索和筛选状态
  const [searchInput, setSearchInput] = useState("");
  const [selectedLevels, setSelectedLevels] = useState<string[]>([]);
  const [selectedTypes, setSelectedTypes] = useState<string[]>([]);
  const [isFilterOpen, setIsFilterOpen] = useState(false);

  // 个性推荐相关状态
  const [recommendations, setRecommendations] = useState<any[]>([]);
  const [recLoading, setRecLoading] = useState(false);
  const [recError, setRecError] = useState<string | null>(null);

  // 智能笔记相关状态
  const [notesView, setNotesView] = useState<'main' | 'text-generate' | 'pdf-generate'>('main');
  const [noteInput, setNoteInput] = useState("");
  const [generatedNote, setGeneratedNote] = useState("");
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const [isDragOver, setIsDragOver] = useState(false);
  const fileUploadRef = useRef<HTMLInputElement>(null);

  // 新增 loading 和 error 状态
  const [noteLoading, setNoteLoading] = useState(false);
  const [noteError, setNoteError] = useState("");

  // 新增：PDF上传成功标志
  const [pdfUploaded, setPdfUploaded] = useState(false);

  // 使用useMemo确保当任务状态改变时重新计算数据
  const weeklyData = useMemo(() => {
    const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    const today = new Date();
    const monday = new Date(today);
    monday.setDate(today.getDate() - (today.getDay() === 0 ? 6 : today.getDay() - 1));

    const data = days.map((day, index) => {
      const currentDate = new Date(monday);
      currentDate.setDate(monday.getDate() + index);
      const dateString = currentDate.toDateString();

      // 根据实际任务计算完成率
      const dayTasks = tasks.filter(task => task.date === dateString);
      const totalTasks = dayTasks.length;
      const completedTasks = dayTasks.filter(task => task.completed).length;
      const completion = totalTasks > 0 ? Number((completedTasks / totalTasks).toFixed(2)) : 0;

      return {
        day,
        date: `${currentDate.getMonth() + 1}.${currentDate.getDate()}`,
        completion
      };
    });
    return data;
  }, [tasks]);


  const toggleTask = (taskId: string) => {
    setTasks(tasks.map(task =>
      task.id === taskId ? { ...task, completed: !task.completed } : task
    ));
  };

  const addTask = () => {
    if (newTaskText.trim()) {
      const newTask: Task = {
        id: Date.now().toString(),
        text: newTaskText,
        completed: false,
        date: selectedDate.toDateString()
      };
      setTasks([...tasks, newTask]);
      setNewTaskText("");
    }
  };

  const deleteTask = (taskId: string) => {
    setTasks(tasks.filter(task => task.id !== taskId));
  };

  const editTask = (taskId: string, newText: string) => {
    setTasks(tasks.map(task =>
      task.id === taskId ? { ...task, text: newText } : task
    ));
  };

  const todayTasks = tasks.filter(task => task.date === selectedDate.toDateString());

  const handleAvatarChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        setUserInfo({ ...userInfo, avatar: e.target?.result as string });
      };
      reader.readAsDataURL(file);
    }
  };

  const sendQuestion = async () => {
    if (questionInput.trim()) {
      const timestamp = Date.now().toString();
      setChatHistory(prev => [
        ...prev,
        { id: `user-${timestamp}`, type: 'user', message: questionInput }
      ]);
      const currentQuestion = questionInput;
      setQuestionInput("");
      setChatHistory(prev => [
        ...prev,
        { id: `ai-${timestamp}`, type: 'ai', message: 'AI正在思考...' }
      ]);
      try {
        const res = await fetch('http://172.20.10.4:8000/query', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            team: 'edu_assistant_team',
            query: currentQuestion
          }),
        });
        const data = await res.json();
        console.log('后端返回的历史会话:', data.history);
        // 替换"AI正在思考..."为真实答案
        setChatHistory(prev => prev.map(item =>
          item.id === `ai-${timestamp}`
            ? { ...item, message: data.response?.final_output || '无回答' }
            : item
        ));
      } catch (error) {
        setChatHistory(prev => prev.map(item =>
          item.id === `ai-${timestamp}`
            ? { ...item, message: 'AI服务请求失败，请稍后重试。' }
            : item
        ));
      }
    }
  };

  // 登录函数，调用后端接口
  const handleLogin = async () => {
    if (!loginUsername || !loginPassword) {
      alert("请输入账号和密码！");
      return;
    }
    const loginId = loginUsername;
    try {
      const res = await fetch('http://localhost:5000/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          id: loginId,
          username: "",
          account: loginUsername,
          password: loginPassword
        })
      });
      const data = await res.json();
      if (data.success) {
        setIsLoggedIn(true);
        setCurrentUser({
          id: data.data.id,
          username: data.data.account,
          password: "",
          profile: { name: data.data.username, gender: "男", avatar: "" }
        });
        setUserInfo({ name: data.data.username, gender: "男", avatar: "" });
        setLoginUsername("");
        setLoginPassword("");
      } else {
        alert(data.message || "账号或密码错误！");
      }
    } catch (err) {
      alert("登录请求失败，请稍后重试。");
    }
  };

  // 注册函数，调用后端接口
  const handleRegister = async () => {
    if (!registerName || !registerUsername || !registerPassword) {
      alert("请填写完整信息！");
      return;
    }
    const newId = Date.now().toString();
    try {
      const res = await fetch('http://localhost:5000/api/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          id: newId,
          username: registerName,
          account: registerUsername,
          password: registerPassword
        })
      });
      const data = await res.json();
      if (data.success) {
        alert("注册成功，请登录。");
        setCurrentView('login');
        setRegisterName("");
        setRegisterUsername("");
        setRegisterPassword("");
      } else {
        alert(data.message || "注册失败");
      }
    } catch (err) {
      alert("注册请求失败，请稍后重试。");
    }
  };

  // 登出函数
  const handleLogout = () => {
    setIsLoggedIn(false);
    setCurrentUser(null);
    setUserInfo({ name: "", gender: "男", avatar: "" });
  };

  // 获取个性推荐内容
  const fetchRecommendations = async (query: string, levels: string[], types: string[]) => {
    setRecLoading(true);
    setRecError(null);
    try {
      const res = await fetch('http://172.20.10.4:8000/query', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          team: 'edu_assistant_team',
          query: query.trim(),
          profile: {
            level: levels[0] ? (levels[0] === 'beginner' ? '入门' : levels[0] === 'intermediate' ? '熟练' : '精通') : '',
            type: types[0] ? (types[0] === 'books' ? '书籍教材' : types[0] === 'videos' ? '视频课程' : '其他') : ''
          }
        })
      });
      const data = await res.json();
      setRecommendations(Array.isArray(data.response) ? data.response : (data.response?.final_output ? [data.response.final_output] : []));
    } catch (err) {
      setRecError('推荐服务请求失败，请稍后重试。');
      setRecommendations([]);
    } finally {
      setRecLoading(false);
    }
  };

  // 清理笔记状态
  const resetNotesState = () => {
    setNoteInput("");
    setGeneratedNote("");
    setUploadedFile(null);
    setIsDragOver(false);
  };

  // 文本生成笔记（提示生成笔记）
  const generateTextNote = async () => {
    if (!noteInput.trim()) return;
    setNoteLoading(true);
    setNoteError("");
    setGeneratedNote("");
    try {
      const res = await fetch('http://172.20.10.4:8000/query', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ query: noteInput })
      });
      const data = await res.json();
      setGeneratedNote(data.markdown || data.response?.final_output || '无内容');
    } catch (err) {
      setNoteError('请求失败，请稍后重试');
    } finally {
      setNoteLoading(false);
    }
  };

  // PDF生成笔记（只做上传，成功后允许输入query）
  const confirmGeneratePDFNote = async () => {
    if (!uploadedFile) return;
    setNoteLoading(true);
    setNoteError("");
    setGeneratedNote("");
    try {
      const formData = new FormData();
      formData.append('file', uploadedFile);
      const res = await fetch('http://172.20.10.4:8000/upload_pdf', {
        method: 'POST',
        body: formData
      });
      await res.json();
      setPdfUploaded(true); // 上传成功
    } catch (err) {
      setNoteError('上传失败，请稍后重试');
      setPdfUploaded(false);
    } finally {
      setNoteLoading(false);
    }
  };

  // 生成笔记逻辑
  const handleGenerateNote = async () => {
    if (!noteInput.trim()) return;
    setNoteLoading(true);
    setNoteError("");
    setGeneratedNote("");
    try {
      const res = await fetch('http://172.20.10.4:8000/generate_note', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          team: 'edu_assistant_team',
          query: noteInput
        })
      });
      const data = await res.json();
      setGeneratedNote(data.markdown || data.response?.final_output || data.content || '无内容');
    } catch (err) {
      setNoteError('请求失败，请稍后重试');
    } finally {
      setNoteLoading(false);
    }
  };

  // 拖拽相关
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(true);
  };
  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
  };
  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
    const file = e.dataTransfer.files[0];
    if (file) handleFileUpload(file);
  };

  // 处理PDF文件选择和拖拽
  const handleFileUpload = (file: File) => {
    if (file.type !== 'application/pdf') {
      alert('请上传PDF文件');
      return;
    }
    setUploadedFile(file);
    setGeneratedNote("");
  };

  // 如果未登录，显示登录/注册界面
  if (!isLoggedIn) {
    return (
      <div className="h-screen bg-gray-50 flex items-center justify-center">
        <div className="w-full max-w-md">
          {currentView === 'login' ? (
            // 登录界面
            <Card className="p-8">
              <CardContent className="space-y-6">
                <div className="text-center">
                  <h1 className="text-3xl font-bold text-gray-800 mb-8">Welcome</h1>
                </div>

                <div className="space-y-4">
                  <Input
                    placeholder="输入账号"
                    value={loginUsername}
                    onChange={(e) => setLoginUsername(e.target.value)}
                    className="h-12"
                  />
                  <Input
                    type="password"
                    placeholder="输入密码"
                    value={loginPassword}
                    onChange={(e) => setLoginPassword(e.target.value)}
                    className="h-12"
                    onKeyPress={(e) => e.key === 'Enter' && handleLogin()}
                  />
                </div>

                <div className="flex gap-4">
                  <Button
                    onClick={handleLogin}
                    className="flex-1 h-12"
                    disabled={!loginUsername || !loginPassword}
                  >
                    登录
                  </Button>
                  <Button
                    variant="outline"
                    onClick={() => setCurrentView('register')}
                    className="flex-1 h-12"
                  >
                    注册
                  </Button>
                </div>
              </CardContent>
            </Card>
          ) : (
            // 注册界面
            <Card className="p-8">
              <CardContent className="space-y-6">
                <div className="space-y-4">
                  <Input
                    placeholder="输入用户名"
                    value={registerName}
                    onChange={(e) => setRegisterName(e.target.value)}
                    className="h-12"
                  />
                  <Input
                    placeholder="输入账号"
                    value={registerUsername}
                    onChange={(e) => setRegisterUsername(e.target.value)}
                    className="h-12"
                  />
                  <Input
                    type="password"
                    placeholder="输入密码"
                    value={registerPassword}
                    onChange={(e) => setRegisterPassword(e.target.value)}
                    className="h-12"
                  />
                </div>

                <div className="flex flex-col gap-4">
                  <Button
                    onClick={handleRegister}
                    className="h-12"
                    disabled={!registerName || !registerUsername || !registerPassword}
                  >
                    注册
                  </Button>
                  <Button
                    variant="outline"
                    onClick={() => setCurrentView('login')}
                    className="h-12"
                  >
                    返回登录
                  </Button>
                </div>
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    );
  }

  return (
    <div className="h-screen bg-gray-50 p-4 overflow-hidden">
      <div className={`w-full grid gap-4 h-screen ${
        activeSection === "qa" ? "grid-cols-1 lg:grid-cols-4" : "grid-cols-1 lg:grid-cols-4"
      }`}>

        {/* 左侧用户信息和导航 */}
        <div className={`space-y-4 ${activeSection === "qa" ? "lg:col-span-1" : ""}`}>
          {/* 用户信息区域 */}
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center space-x-3 mb-4">
                <Dialog>
                  <DialogTrigger asChild>
                    <Avatar className="h-16 w-16 cursor-pointer">
                      <AvatarImage src={userInfo.avatar} />
                      <AvatarFallback>头像</AvatarFallback>
                    </Avatar>
                  </DialogTrigger>
                  <DialogContent>
                    <DialogHeader>
                      <DialogTitle>头像设置</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4">
                      <Avatar className="h-24 w-24 mx-auto">
                        <AvatarImage src={userInfo.avatar} />
                        <AvatarFallback>头像</AvatarFallback>
                      </Avatar>
                      <Button onClick={() => fileInputRef.current?.click()} className="w-full">
                        更换头像
                      </Button>
                      <input
                        ref={fileInputRef}
                        type="file"
                        accept="image/*"
                        onChange={handleAvatarChange}
                        className="hidden"
                      />
                    </div>
                  </DialogContent>
                </Dialog>

                <div className="flex-1">
                  <div className="text-sm text-gray-700">昵称: {currentUser?.profile.name}</div>
                </div>
              </div>
              <div className="flex justify-center">
                <Button onClick={handleLogout} variant="outline" size="sm" className="w-full">
                  登出
                </Button>
              </div>
            </CardContent>
          </Card>

          {/* 功能导航 */}
          <Card>
            <CardContent className="p-4 space-y-2">
              <Button
                variant={activeSection === "qa" ? "default" : "outline"}
                className="w-full justify-start"
                onClick={() => setActiveSection(activeSection === "qa" ? "" : "qa")}
              >
                <Diamond className="mr-2 h-4 w-4" />
                智能问答
              </Button>
              <Button
                variant={activeSection === "recommend" ? "default" : "outline"}
                className="w-full justify-start"
                onClick={() => setActiveSection(activeSection === "recommend" ? "" : "recommend")}
              >
                <Diamond className="mr-2 h-4 w-4" />
                个性推荐
              </Button>
              <Button
                variant={activeSection === "notes" ? "default" : "outline"}
                className="w-full justify-start"
                onClick={() => setActiveSection(activeSection === "notes" ? "" : "notes")}
              >
                <Diamond className="mr-2 h-4 w-4" />
                智能笔记
              </Button>
            </CardContent>
          </Card>
        </div>

        {/* 中间内容区域 */}
        <div className={`space-y-4 ${activeSection === "qa" || activeSection === "recommend" || activeSection === "notes" ? "lg:col-span-3" : "lg:col-span-2"}`}>
          {/* 本周学习情况 - 只在没有激活专属功能时显示 */}
          {!activeSection && (
            <Card>
              <CardHeader>
                <CardTitle>本周学习情况</CardTitle>
              </CardHeader>
              <CardContent>
              <div className="space-y-4">
                <div className="text-sm text-gray-600">任务完成情况</div>

                {/* 折线图区域 */}
                <div className="relative h-56 bg-gray-50 rounded-lg">
                  {/* Y轴标签和网格线绝对对齐 */}
                  <div className="absolute left-0 top-0 h-full w-8">
                    {[1.0, 0.8, 0.6, 0.4, 0.2, 0.0].map((value, index) => (
                      <div key={value} style={{ position: 'absolute', top: `calc(${(index / 5) * 100}% - 8px)` }}>
                        <span className="text-xs text-gray-400">{value}</span>
                  </div>
                    ))}
                  </div>
                  <div className="absolute left-8 top-0 right-0 bottom-16">
                  {/* 网格线 */}
                    <div className="absolute inset-0">
                      {[1.0, 0.8, 0.6, 0.4, 0.2, 0.0].map((value, index) => (
                        <div
                          key={value}
                          className="absolute w-full border-t border-gray-200"
                          style={{ top: `calc(${(index / 5) * 100}% - 0.5px)`, height: '1px' }}
                        />
                      ))}
                  </div>

                  {/* 折线图 */}
                    <svg className="absolute inset-0 w-full h-full" viewBox="0 0 100 100" preserveAspectRatio="none">
                      <polyline
                        fill="none"
                        stroke="#3b82f6"
                        strokeWidth="0.5"
                        points={weeklyData.map((item, index) =>
                          `${(index / (weeklyData.length - 1)) * 100},${Math.max(0, Math.min(100, 100 - item.completion * 100))}`
                        ).join(' ')}
                      />
                      {weeklyData.map((item, index) => (
                        <circle
                          key={item.day}
                          cx={Math.max(0, Math.min(100, (index / (weeklyData.length - 1)) * 100))}
                          cy={Math.max(0, Math.min(100, 100 - item.completion * 100))}
                          r="1"
                          fill="#3b82f6"
                          className="hover:r-2 transition-all"
                        />
                      ))}
                    </svg>

                    {/* 完成率数字 */}
                    {weeklyData.map((item, index) => (
                        <div
                        key={item.day}
                        className="absolute text-xs font-medium text-blue-600"
                          style={{
                          left: `${Math.max(0, Math.min(100, (index / (weeklyData.length - 1)) * 100))}%`,
                          top: `${Math.max(0, Math.min(100, 100 - item.completion * 100 - 18))}%`,
                            transform: 'translateX(-50%)'
                          }}
                        >
                          {item.completion}
                      </div>
                    ))}
                  </div>
                      </div>
              </div>
            </CardContent>
          </Card>
          )}

          {/* 动态内容区域 */}
          {activeSection === "qa" && (
            <Card className="h-full flex flex-col">
              <CardHeader>
                <CardTitle>智能问答</CardTitle>
              </CardHeader>
              <CardContent className="flex-1 flex flex-col space-y-4">
                {/* 对话历史区域 - 占据大部分空间 */}
                <div className="flex-1 min-h-[400px] max-h-[600px] overflow-y-auto custom-scrollbar space-y-3 bg-gray-50 rounded-lg p-4">
                  {chatHistory.length === 0 ? (
                    <div className="text-center text-gray-500 py-8">
                      <div className="text-lg mb-2">👋 欢迎使用智能问答</div>
                      <div className="text-sm">您可以向我提问任何学习相关的问题</div>
                    </div>
                  ) : (
                    chatHistory.map((item) => (
                      <div key={item.id} className={`flex ${item.type === 'user' ? 'justify-end' : 'justify-start'}`}>
                        <div className={`max-w-[80%] p-3 rounded-lg ${
                          item.type === 'user'
                            ? 'bg-blue-500 text-white'
                            : 'bg-white text-gray-800 shadow-sm border'
                        }`}>
                          {item.type === 'ai' && (
                            <div className="flex items-center mb-2">
                              <div className="w-6 h-6 bg-gray-600 rounded-full flex items-center justify-center text-white text-xs mr-2">
                                AI
                              </div>
                              <span className="text-sm font-medium">AI助手</span>
                            </div>
                          )}
                          {item.type === 'ai' ? (
                            <div className="prose max-w-none">
                              <ReactMarkdown>{item.message}</ReactMarkdown>
                            </div>
                          ) : (
                            item.message
                          )}
                        </div>
                      </div>
                    ))
                  )}
                </div>

                {/* 输入区域 - 固定在底部 */}
                <div className="space-y-3 bg-white border rounded-lg p-4">
                  <div className="flex space-x-2">
                    <Input
                      placeholder="请输入您的问题..."
                      value={questionInput}
                      onChange={(e) => setQuestionInput(e.target.value)}
                      onKeyPress={(e) => e.key === 'Enter' && sendQuestion()}
                      className="flex-1"
                    />
                    <Button onClick={sendQuestion} disabled={!questionInput.trim()}>
                      发送
                    </Button>
                  </div>
                  <div className="text-xs text-gray-400 text-center">
                    按 Enter 键发送消息
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          {activeSection === "recommend" && (
            <Card className="h-full flex flex-col">
              <CardHeader>
                <CardTitle>个性推荐</CardTitle>
              </CardHeader>
              <CardContent className="flex-1 flex flex-col space-y-6">
                {/* 搜索栏和筛选按钮 */}
                <div className="bg-white border rounded-lg p-4">
                  <div className="flex gap-3 mb-4">
                    <div className="flex-1 relative">
                      <Input
                        placeholder="输入搜索内容"
                        value={searchInput}
                        onChange={(e) => setSearchInput(e.target.value)}
                        className="pr-12"
                      />
                      <div
                        className="absolute right-3 top-1/2 transform -translate-y-1/2 w-6 h-6 bg-gray-100 rounded flex items-center justify-center cursor-pointer hover:bg-gray-200 transition-colors"
                        onClick={() => fetchRecommendations(searchInput, selectedLevels, selectedTypes)}
                      >
                        <svg className="w-4 h-4 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                        </svg>
                      </div>
                    </div>
                    <Button
                      variant="outline"
                      className="flex items-center gap-2"
                      onClick={() => setIsFilterOpen(!isFilterOpen)}
                    >
                      更多筛选
                      <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clipRule="evenodd" />
                      </svg>
                    </Button>
                  </div>

                  {/* 筛选选项展开区域 */}
                  {isFilterOpen && (
                    <div className="space-y-4 pb-4 border-b">
                      {/* 水平筛选 */}
                      <div className="flex items-center gap-4">
                        <div className="text-sm font-medium w-12 text-gray-700">水平</div>
                        <div className="flex gap-3">
                          {[
                            { value: "beginner", label: "入门" },
                            { value: "intermediate", label: "熟练" },
                            { value: "advanced", label: "精通" }
                          ].map((level) => (
                            <div
                              key={level.value}
                              onClick={() => {
                                if (selectedLevels.includes(level.value)) {
                                  setSelectedLevels(selectedLevels.filter(l => l !== level.value));
                                } else {
                                  setSelectedLevels([...selectedLevels, level.value]);
                                }
                              }}
                              className={`w-28 px-4 py-2 rounded border cursor-pointer transition-colors text-center ${
                                selectedLevels.includes(level.value)
                                  ? 'bg-blue-100 border-blue-300 text-blue-700'
                                  : 'bg-white border-gray-300 hover:bg-gray-50'
                              }`}
                            >
                              {level.label}
                            </div>
                          ))}
                        </div>
                      </div>

                      {/* 类型筛选 */}
                      <div className="flex items-center gap-4">
                        <div className="text-sm font-medium w-12 text-gray-700">类型</div>
                        <div className="flex gap-3">
                          {[
                            { value: "books", label: "书籍教材" },
                            { value: "videos", label: "视频课程" },
                            { value: "others", label: "其他" }
                          ].map((type) => (
                            <div
                              key={type.value}
                              onClick={() => {
                                if (selectedTypes.includes(type.value)) {
                                  setSelectedTypes(selectedTypes.filter(t => t !== type.value));
                                } else {
                                  setSelectedTypes([...selectedTypes, type.value]);
                                }
                              }}
                              className={`w-28 px-4 py-2 rounded border cursor-pointer transition-colors text-center ${
                                selectedTypes.includes(type.value)
                                  ? 'bg-blue-100 border-blue-300 text-blue-700'
                                  : 'bg-white border-gray-300 hover:bg-gray-50'
                              }`}
                            >
                              {type.label}
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  )}

                  {/* 已选筛选条件显示 */}
                  {(selectedLevels.length > 0 || selectedTypes.length > 0) && (
                    <div className="flex flex-wrap gap-2 text-sm pt-4 border-t">
                      <span className="text-gray-600">已选择：</span>
                      {selectedLevels.map(level => (
                        <span key={level} className="bg-blue-100 text-blue-700 px-2 py-1 rounded text-xs">
                          {level === 'beginner' ? '入门' : level === 'intermediate' ? '熟练' : '精通'}
                        </span>
                      ))}
                      {selectedTypes.map(type => (
                        <span key={type} className="bg-blue-100 text-blue-700 px-2 py-1 rounded text-xs">
                          {type === 'books' ? '书籍教材' : type === 'videos' ? '视频课程' : '其他'}
                        </span>
                      ))}
                    </div>
                  )}
                </div>

                {/* 推荐内容区域 */}
                <div className="flex-1 bg-gray-50 rounded-lg p-6 custom-scrollbar max-h-[70vh] overflow-y-auto">
                  <div className="mb-4">
                    <div className="text-lg font-medium">📚 推荐内容</div>
                    <div className="text-sm text-gray-600">
                      {searchInput && `搜索："${searchInput}" `}
                      {(selectedLevels.length > 0 || selectedTypes.length > 0) && "· 根据筛选条件匹配"}
                      {!searchInput && selectedLevels.length === 0 && selectedTypes.length === 0 && "显示所有推荐内容"}
                    </div>
                  </div>
                  {recLoading ? (
                    <div className="text-center text-gray-500 py-8">推荐内容加载中...</div>
                  ) : recError ? (
                    <div className="text-center text-red-500 py-8">{recError}</div>
                  ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      {recommendations.length > 0 ? recommendations.map((item, index) => (
                        <div key={index} className="bg-white p-4 rounded-lg shadow-sm border hover:shadow-md transition-shadow cursor-pointer">
                          {/* 优先渲染 markdown 内容 */}
                          {item.markdown || typeof item === 'string' ? (
                            <div className="prose max-w-none">
                              <ReactMarkdown>{item.markdown || item}</ReactMarkdown>
                            </div>
                          ) : (
                            <>
                              <div className="font-medium mb-2 flex items-center">
                                <span className="mr-2">{item.type || '📚'}</span>
                                {item.title || ''}
                        </div>
                        <div className="text-sm text-gray-600 mb-2">
                                {item.description || ''}
                        </div>
                        <div className="flex gap-2 mb-3">
                                {item.level && <span className="text-xs px-2 py-1 rounded bg-blue-100 text-blue-700">{item.level}</span>}
                                {item.category && <span className="text-xs px-2 py-1 rounded bg-blue-100 text-blue-700">{item.category}</span>}
                        </div>
                        <div className="mt-3">
                          <Button size="sm" variant="outline" className="text-xs">
                            查看详情
                          </Button>
                        </div>
                            </>
                          )}
                      </div>
                      )) : (
                    <div className="text-center text-gray-500 py-8">
                      <div className="text-lg mb-2">暂无匹配内容</div>
                      <div className="text-sm">请尝试调整搜索关键词或筛选条件</div>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          )}

          {activeSection === "notes" && (
            <Card className="h-full flex flex-col">
              <CardHeader>
                <CardTitle>智能笔记</CardTitle>
              </CardHeader>
              <CardContent className="flex-1 flex flex-col">
                <div className="flex-1 flex flex-col">
                  <div className="mb-6">
                    <input
                      type="file"
                      ref={fileUploadRef}
                      accept=".pdf"
                      className="hidden"
                      onChange={(e) => {
                        const file = e.target.files?.[0];
                        if (file) handleFileUpload(file);
                      }}
                    />
                  </div>
                  <div className="flex flex-1 gap-4">
                    {/* 左侧：上传和生成区域 */}
                    <div className="flex-1 flex flex-col">
                      <div
                        className={`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${isDragOver ? 'border-blue-400 bg-blue-50' : 'border-gray-300 hover:border-gray-400'}`}
                        onClick={() => fileUploadRef.current?.click()}
                        onDragOver={handleDragOver}
                        onDragLeave={handleDragLeave}
                        onDrop={handleDrop}
                      >
                        <div className="text-4xl mb-4">📄</div>
                        <div className="text-lg font-medium mb-2">上传你的PDF文件</div>
                        <div className="text-sm text-gray-500">点击选择文件或拖拽文件到此处</div>
                        {uploadedFile && (
                          <div className="mt-4 text-sm text-green-600">已上传: {uploadedFile.name}</div>
                        )}
                      </div>
                      {/* 确认按钮 */}
                      {uploadedFile && !pdfUploaded && (
                        <div className="mt-4 flex justify-center">
                          <Button onClick={confirmGeneratePDFNote} className="px-8 py-2" disabled={noteLoading}>
                            确认上传并生成笔记入口
                          </Button>
                        </div>
                      )}
                      {/* 上传成功后显示query输入框和生成按钮 */}
                      {pdfUploaded && (
                        <div className="mt-6 flex gap-2">
                          <Input
                            placeholder="请输入你的需求，如：生成语文笔记、生成数学知识点总结..."
                            value={noteInput}
                            onChange={e => setNoteInput(e.target.value)}
                            onKeyPress={e => e.key === 'Enter' && handleGenerateNote()}
                            className="flex-1"
                          />
                          <Button onClick={handleGenerateNote} disabled={!noteInput.trim() || noteLoading}>
                            生成笔记
                          </Button>
                        </div>
                      )}
                      <div className="flex-1 border rounded-lg p-4 bg-gray-50 overflow-y-auto custom-scrollbar mt-4" style={{maxHeight: '60vh'}}>
                        {noteLoading ? (
                          <div className="text-center text-gray-500 py-8">笔记生成中...</div>
                        ) : noteError ? (
                          <div className="text-center text-red-500 py-8">{noteError}</div>
                        ) : generatedNote ? (
                          <div className="prose max-w-none"><ReactMarkdown>{generatedNote}</ReactMarkdown></div>
                        ) : (
                          <div className="text-center text-gray-500 py-8">
                            <div className="text-lg mb-2">{pdfUploaded ? '请输入问题并生成学习笔记' : '上传PDF文件后自动生成学习笔记'}</div>
                          </div>
                        )}
                      </div>
                    </div>
                    {/* 右侧：PDF预览区域 */}
                    <div className="flex-1 border rounded-lg bg-white flex items-center justify-center overflow-hidden h-full" style={{minWidth: 0, height: 'calc(100vh - 200px)'}}>
                      {uploadedFile ? (
                        <embed
                          src={URL.createObjectURL(uploadedFile)}
                          type="application/pdf"
                          width="100%"
                          height="100%"
                          style={{ minHeight: '400px', height: '100%', width: '100%' }}
                        />
                      ) : (
                        <div className="text-gray-400 text-center w-full">请上传PDF后预览原文</div>
                      )}
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}
        </div>

        {/* 右侧日历和任务 - 专属功能激活时隐藏 */}
        {!activeSection && (
          <div className="space-y-4">
          {/* 本月日历 */}
          <Card>
            <CardHeader>
              <CardTitle>本月日历</CardTitle>
            </CardHeader>
            <CardContent>
              <Calendar
                mode="single"
                selected={selectedDate}
                onSelect={(date) => date && setSelectedDate(date)}
                className="rounded-md border w-full"
              />
            </CardContent>
          </Card>

          {/* 本日任务 */}
          <Card>
            <CardHeader>
              <CardTitle>本日任务</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              {todayTasks.map((task) => (
                <ContextMenu key={task.id}>
                  <ContextMenuTrigger>
                    <div className="flex items-center space-x-3 p-2 hover:bg-gray-100 rounded">
                      <Button
                        variant="outline"
                        size="sm"
                        className="p-0 h-6 w-6"
                        onClick={() => toggleTask(task.id)}
                      >
                        <Diamond className={`h-3 w-3 ${task.completed ? 'fill-green-500 text-green-500' : ''}`} />
                      </Button>
                      <span className={`flex-1 ${task.completed ? 'line-through text-gray-500' : ''}`}>
                        {task.text}
                      </span>
                    </div>
                  </ContextMenuTrigger>
                  <ContextMenuContent>
                    <ContextMenuItem onClick={() => {
                      const newText = prompt("编辑任务", task.text);
                      if (newText) editTask(task.id, newText);
                    }}>
                      编辑
                    </ContextMenuItem>
                    <ContextMenuItem onClick={() => deleteTask(task.id)}>
                      删除
                    </ContextMenuItem>
                  </ContextMenuContent>
                </ContextMenu>
              ))}

              <div className="flex items-center space-x-2 mt-4">
                <Input
                  placeholder="添加新任务"
                  value={newTaskText}
                  onChange={(e) => setNewTaskText(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && addTask()}
                />
                <Button onClick={addTask} size="sm" className="p-0 h-8 w-8 rounded-full">
                  <Plus className="h-4 w-4" />
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
        )}
      </div>
    </div>
  );
}
